const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const process = require('child_process');

let lock = false;
let hasTask = false;
let password = "dba577f445aef58b32b*****a966b76d";

function update() {
    if (lock) {
        hasTask = true;
        return;
    }
    lock = true;
    process.exec("./update.sh", (err, stdout, stderr) => {
        console.log(stdout);
        console.log(stderr);
	lock = false;
        if (hasTask) {
            hasTask = false;
            update();            
        }
    })
}

router.post('/hook', async (ctx, next) => {
    if (ctx.req.headers['x-gitee-token'] == password) { 
        update();
    }
    ctx.response.body = "OK";
});

app.use(bodyParser({
    onerror: (err) => {
        console.log(err);
    },
    enableTypes: ['json'] 
}));
app.use(router.routes());

app.listen(3000, "0.0.0.0", () => {
    console.log('listening @ 3000...')
})
